/**
 * 
 */

$(function(){
	initMap();
});
var map, geolocation = null;
var myBike = {};
myBike.showSetting = {
		state : 1,// 默认显示正常
};
myBike.markers = {
		exceptionMarker : new Array(),
		normalMarker : new Array(),
};
var MyBike = {};

MyBike.Site = {
	_value : new Array(),
	init:function(){
		return this;
	},
	getAllSite : function() {
		var siteData = new Array();
		$.post('getBikeSite.do', {},  function (data) {
			var json = eval('(' + data + ')');
			siteData.concat(json);
			this._value = siteData;
		});
	}
};

function searchBike(valLng, valLat){
	$.ajax({
		 type:'post',
		 url:'getSearch',
		 data:{
			 lng:valLng,
			 lat:valLat,
			 radius:"2000"
		 },
		 dataType:'json',
		 success:function(data){
			 siteData = data;
			 if(null != myBike.markers.normalMarker && myBike.markers.normalMarker.length > 0){
				 clearMap(myBike.markers.normalMarker);
			 }
				if(null != myBike.markers.exceptionMarker && myBike.markers.exceptionMarker.length > 0){
				 clearMap(myBike.markers.exceptionMarker);
			 }
			for(var i = 0; i < siteData.length; i++){
				 var siteInfo = siteData[i];
				 siteInfo.isNormal = 'exception';
				 if(siteInfo.siteState == 1){
					 siteInfo.isNormal = 'normal';
				 }
				 siteInfo.id = i;
				 addMarker(siteInfo);
			}
			map.setFitView();
		 }
	 });  
}





// 初始化地图
function initMap(){
	map = new AMap.Map('myMap', {
        resizeEnable: true,
        zoom:11,
        center: [108.942531,34.270538],
        scrollWheel:true,
    });
	
	map.on('complete', function() {
        //设置城市
        map.setCity('西安市');
        initCurrentPosition();// 获取用户当前GPS位置
    });
}

$('#reload-local').on('click',function (){
	map.setCenter(myLocal.getPosition());
	nowZoom = 17;
	map.setZoom(nowZoom);
});

//初始化当前位置
function initCurrentPosition(){
	map.plugin('AMap.Geolocation', function () {
	    geolocation = new AMap.Geolocation({
	        enableHighAccuracy: true,//是否使用高精度定位，默认:true
	        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
	        maximumAge: 0,           //定位结果缓存0毫秒，默认：0
	        convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
	        showButton: true,        //显示定位按钮，默认：true
	        buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
	        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
	        showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
	        showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
	        panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
	        zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
	    });
	    //map.addControl(geolocation);
	    geolocation.getCurrentPosition();
	    AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
	    AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
	});
}
var myLocal = null;
//解析定位结果
function onComplete(data) {
	
	map.setCenter([data.position.getLng(), data.position.getLat()]);
    if(null == myLocal){
    	
    	myLocal = new AMap.Marker({
            position: [data.position.getLng(), data.position.getLat()],
            draggable: false,
            cursor: 'move',
            icon: 'http://ditu.amap.com/assets/img/loc_ok.png'
        });
    	// 设置鼠标划过点标记显示的文字提示
        myLocal.setTitle('我的位置');
        myLocal.setMap(map);
        map.setZoom(16);
    } else {
    	myLocal.setPosition([data.position.getLng(), data.position.getLat()]);
    }
	// 设置label标签
    /*marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
        content: "<span style='font-size:10px;font-color:red;'>我的当前位置o(^▽^)o</span>"
    });*/
    // 初始化点
    var newCenter = map.setFitView();
    searchBike(data.position.getLng(), data.position.getLat());
}



//解析定位错误信息
function onError(data) {//108.913866,34.206807
	//console.log(str.join('定位失败'));
	searchBike(108.913866,34.206807);
	//alert('定位异常');
}

var infoWindow = new AMap.InfoWindow({
	offset: new AMap.Pixel(0, -30),
	closeWhenClickMap:true,
});

function addMarker(siteData) {
	var siteInfo = siteData;
	var title = '' + siteInfo.sitename, content = [];
	var lnglat = new AMap.LngLat(siteInfo.longitude, siteInfo.latitude);
	var id = "marker_bike_" + siteInfo.id;
	var siteState = 1;
	var icon = './resources/images/zxc_g1.png';
	
	if ('normal' == siteInfo.isNormal) {
		id = "marker_bike_" + siteInfo.id;
	} else if ('exception' == siteInfo.isNormal) {
		id = "marker_exception_bike_" + siteInfo.id;
		icon = './resources/images/zxc_r1.png';
		siteState = 2;
	} else {
		id = "marker_all_bike_" + siteInfo.id;
		icon = './resources/images/zxc_r1.png';
		siteState = 2;
	}

	var marker = new AMap.Marker({
		id : id,
		siteState : siteState,
		icon : icon,
		position : lnglat,
		map : map
	});
	marker.siteId = siteData.siteid;
	closeInfoWindow();
	// 鼠标点击marker弹出自定义的信息窗体
	AMap.event.addListener(marker, 'click', function(e) {
		map.setCenter(e.target.getPosition());
		if(map.getZoom() < 17){
			map.setZoom(17);
		};
		map.setFitView(e.target.getPosition());
		var content = getWindowInfoContent(e.target.siteId);
		infoWindow.setContent(content);
		infoWindow.open(map, e.target.getPosition());
	});// 注册监听，当选中某条记录时会触发
	var showSetting = myBike.showSetting.state;
	if (showSetting == 1) {
		myBike.markers.normalMarker.push(marker);
	} else if (showSetting == 2) {
		myBike.markers.exceptionMarker.push(marker);
	}
}

function getWindowInfoContent(siteId){
	 var url = "get/site/"+siteId;
	 var result = $.ajax({
		 type:'post',
		 url:url,
		 data:{},
		 async:false,
		 dataType:'json'
	 });
	 var data = null;
	 if(result && result.responseText){
		 data = JSON.parse(result.responseText);
	 }
	 if(data){
		 var content = [];
		 content.push("<div style='font-size:10px;'>");
		 content.push("网点状态："+(data.siteState=='1'?'正常':'异常'));
		 content.push("网点编号："+siteId);
		 content.push("网点名称："+data.sitename);
		 content.push("网点地址："+data.location);
		 content.push("可租车辆数："+(data.locknum-data.emptynum));
		 content.push("可还空位数："+data.emptynum);
		 content.push("更新时间："+data.updateTime);
		 content.push("</div>");
		 
	 }
	 var html = "";
	 html = content.join("<br/>");
	 return html;
}

// 关闭信息窗体
function closeInfoWindow() {
	map.clearInfoWindow();
}

//删除地图上制定覆盖物
function clearMap(overlayers) {
	map.remove(overlayers)
}
//删除地图上所有的覆盖物
function clearMapAll() {
	map.clearMap();
}
